<template>
  <div>
    <Subscribe/>
  </div>
</template>

<script lang="ts">
export default {
  name: "DeviceSubscribe"
}
</script>
<script lang="ts" setup>
import {onMounted, onUnmounted, onBeforeUnmount, defineProps, ref, unref, watch} from "vue";
import {string} from "vue-types";
import {useSubscribeDataStore} from "@/stores/subscribeData";

const props = defineProps({
  topic: string()
})

const {topic} = props
const subscribeDataStore = useSubscribeDataStore();


const subscribe = () => {
  try {
    subscribeDataStore.getSseEmitterHandler?.subscribe?.(topic)
  } catch (e) {
    console.log('subscribe', e)
  }
}

const unSubscribe = () => {
  try {
    subscribeDataStore?.getSseEmitterHandler?.unSubscribe?.(topic)
  } catch (e) {
    console.log('unSubscribe', e)
  }
}

// const timerStopHandler = new TimerStopHandler(subscribe)

// watch(() => props.topic, val => {
//   trackGps({deviceNo: topic}).catch(e => e)
// })

watch(() => {
  const handler = subscribeDataStore.getSseEmitterHandler
  if (!handler?.eventSource || handler?.eventSource === 2) {
    return null
  }
  return handler
}, handler => {
  if (handler?.subscribe) {
    try {
      subscribe()
    } catch (e) {
      console.log('subscribe', e)
    }

  }
})

onMounted(() => {

})

onBeforeUnmount(() => {
  console.log('onBeforeUnmount', topic)
})
onUnmounted(() => {
  console.log('onUnmounted', topic)
  // subscribeDataStore.getSseEmitterHandler?.unSubscribe(topic)
  unSubscribe()
  // console.log('DeviceSubscribe onUnmounted', topic)
})
</script>
<style scoped>

</style>
